from fastapi import APIRouter, Depends
from typing import Annotated
from app.api.deps import SessionDep
from app.schemas.uc.auth import Token
from app.core.config import settings
from app.core.security import create_access_token
from app.core.logger import logger
from fastapi.security import OAuth2PasswordRequestForm
from datetime import timedelta
from fastapi import HTTPException, status
from app.crud.uc.user import get_user_by_mobile
from app.schemas.uc.auth import XmLoginRequest, WpLoginRequest
from app.api.deps import CurrentUser
from app.services.user_service import xm_user_login
from app.crud.uc.partner_token import get_partner_token, create_partner_token, update_partner_token
from app.core.constants import ThirdPartner
from datetime import datetime
from app.schemas.uc.partner_token import PartnerTokenUpdate, PartnerTokenCreate
from app.services.wp_service import get_wp_access_token

router = APIRouter(tags=["auth"], prefix="/auth")

@router.post("/login")
async def login_access_token(
    session: SessionDep, form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
) -> Token:
    """
    OAuth2 compatible token login, get an access token for future requests
    """
    logger.info(f"Login attempt for email: {form_data.username}")
    # user = await authenticate(
    #     session=session, mobile=form_data.username, password=form_data.password
    # )
    user = await get_user_by_mobile(session=session, mobile=form_data.username)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect mobile or password")
    elif user.status != 0:
        raise HTTPException(status_code=400, detail="Inactive user")
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    return Token(
        access_token=create_access_token(
            user.uid, expires_delta=access_token_expires
        )
    )

@router.post("/xm_login", status_code=status.HTTP_200_OK)
async def xm_login_access_token(
    session: SessionDep, form_data: XmLoginRequest
) -> Token:
    """
    XM用户登录，获取访问令牌
    """
    logger.info(f"Login attempt for mobile: {form_data.mobile}")
    user = await xm_user_login(
        session=session, mobile=form_data.mobile, xm_token=form_data.xmToken
    )
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    return Token(
        access_token=create_access_token(
            user.uid, expires_delta=access_token_expires
        )
    )

@router.post("/refresh")
async def refresh_access_token(
    current_user: CurrentUser
) -> Token:
    """
    刷新用户Token
    """
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    return Token(
        access_token=create_access_token(
            current_user.id, expires_delta=access_token_expires
        )
    )

@router.post("/wp_login", status_code=status.HTTP_200_OK)
async def wp_login_access_token(
    session: SessionDep, 
    form_data: WpLoginRequest,
    current_user: CurrentUser
) -> Token:
    """
    WP用户登录，获取访问令牌
    """
    logger.info(f"Login attempt for authCode: {form_data.authCode}")
    # 调用WP接口获取访问令牌
    res = await get_wp_access_token(form_data.authCode)
    logger.info(f"res: {res}")
    # res_str = "{'data': {'accessToken': 'eyJhbGciOiJIUzUxMiJ9.eyJjbGllbnRJZCI6ImFrXzh4OXkyYjdtNG42ZDNwNXExcjBzIiwic2NvcGUiOiJyZWFkIiwiZXhwIjoxNzY0OTE2NTkyLCJ1c2VySWQiOjE5ODgxMzgzMjA1NDg5MzM2MzMsImlhdCI6MTc2MzYyMDU5Mn0.7qaahWbslWZRM13tUbsnqEO85uUXnoMhn254kwWxzNxxFd9y-JCv_z8BMFIXzq7HHu98WpfknqwYFYGCjeFj7A', 'accessExpireTime': '2025-12-05 14:36:32'}, 'rc': 0, 'success': True}"
    # res = ast.literal_eval(res_str)
    if not res:
        raise HTTPException(status_code=400, detail="WP登录失败")
    accessToken = res["data"]["accessToken"]
    if not accessToken:
        raise HTTPException(status_code=400, detail="WP登录失败")
    # 更新WP Token
    localToken = await get_partner_token(
        session=session,
        uid=current_user.uid,
        partner=ThirdPartner.WaveUp,
    )
    if not localToken:
        # 新增本地缓存数据
        token_create = PartnerTokenCreate(
            uid=current_user.uid,
            partner=ThirdPartner.WaveUp,
            accessToken=accessToken,
            expiresAt= res['data']['accessExpireTime'],
        )
        await create_partner_token(
            session=session,
            token_create=token_create,
        )
    else:
        # 更新本地缓存数据
        token_update = PartnerTokenUpdate(
            accessToken=accessToken,
            expiresAt= res['data']['accessExpireTime'],
        )
        await update_partner_token(
            session=session,
            uid=current_user.uid,
            partner=ThirdPartner.WaveUp,
            partner_token=token_update,
        )
    return Token(access_token=accessToken)

@router.post("/check/wp_token", status_code=status.HTTP_200_OK)
async def check_wp_token(
    session: SessionDep,
    current_user: CurrentUser
) -> bool:
    """
    检查WP Token是否过期
    """
    # 查询用户本地缓存Token
    wp_token = await get_partner_token(
        session=session,
        uid=current_user.uid,
        partner=ThirdPartner.WaveUp,
    )
    if not wp_token:
        raise HTTPException(status_code=400, detail="WP Token不存在")
    
    # 本地校验是否过期
    if wp_token.expiresAt <= datetime.now():
        raise HTTPException(status_code=400, detail="WP Token已过期")
    
    return True
    
    # 检查WP Token是否过期
    # 通过调用WaveUp接口检查Token是否过期
    # res = await get_wp_user_info(wp_token.accessToken)
    # if not res or res["rc"] != 0:
    #     raise HTTPException(status_code=400, detail="WP Token过期")
    # return True